<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use app\lib\functions;
use Illuminate\Support\Facades\Schema;
use Qiniu\Auth;


class Controller extends BaseController
{
    public $data;
    const  Coin_Recharge                = '_V1';
    const  Doll_Exchange_Score          = '_V3';
    const  Other_Exchange_Score         = '_V4';#其他兑换
    const  Sign_Score_add               = '_V5';#签到
    const  Mail_ORDER                   = '_V7';#邮寄
    const  Picks_Up_By_Oneself          = '_V8';#自提
    const  Use_Point                    = '_V9';#次元币消费
    const  Coin_TO_Point                = '_V10';#锄头消费
    const  Use_coin_playGame            = '_V11';#游戏订单
    const  Point_Get_PlayGame           = '_V12';#充值返次元币
    public function __construct()
    {
        error_reporting(E_ERROR);
    }

    public static function admin_response($data = null,$ret='200',$msg='操作成功')
    {
        if (empty($data)) {
            $res =  ['ret'=>intval($ret),'msg'=>$msg,'data'=>[]];
        } else {
            $res =  ['ret'=>intval($ret),'msg'=>$msg,'data'=>$data];
        }
        return response(json_encode($res,JSON_UNESCAPED_UNICODE))
            ->header('Content-Type', 'application/json')
            ->header('Charset','UTF-8');
    }

    public static function response($data = null,$ret='200',$msg='操作成功')
    {
        if (!empty($data)&&!is_object($data)&&!is_array($data)){
            throw new  \ErrorException('data类型错误');
        }
        $debug = session('debug');
        if (empty($data)) {
            if (is_object ($data)){
                $res =  ['ret'=>intval($ret),'msg'=>$msg,'debug'=>$debug,'data'=>new \stdClass()];
            }else{
                $res =  ['ret'=>intval($ret),'debug'=>$debug,'msg'=>$msg,'data'=>[]];
            }
        }else{
            $res =  ['ret'=>intval($ret),'msg'=>$msg,'debug'=>$debug,'data'=>$data];
        }
        if (!empty($res['data']) && is_array($res['data'])) {
            foreach ($res['data'] as  &$val) {
                if (is_numeric ( $val )||is_bool ($val)) {
                    $val = strval($val);
                }elseif (is_Null($val)){
                    $val = "null";
                }elseif (is_array ($val)){
                    $val = self::changeString($val);
                }else{

                }
            }
        }
        if ($debug){
            $out             = $res;
        }else{
            $json           = json_encode($res);
            $key            = md5(date('Ymd'));
            $out            = base64_encode ($json).$key;
        }

        return response(['result'=>$out])
            ->header('Content-Type', 'application/json')
            ->header('Charset','UTF-8')
            ->header('server_time',time())
            ->header('timezone',date_default_timezone_get())
            ->header('debug',session('debug'));
    }

    public static function changeString($array)
    {
        foreach ($array as  $key=>$val) {
            if (is_numeric ( $val )||is_bool ($val)) {
                $array[$key] = strval($val);
            }elseif (is_Null($val)||empty($val)){
                $array[$key] = "null";
            }elseif(is_array($val)){
                $array[$key] = self::changeString($val);
            }else{

            }
        }
        return $array;
    }


    public static function Token(int $user_id,$ip)
    {
        //$str = md5(uniqid(md5(microtime(true)),true));  //生成一个不会重复的字符串
        //$str = sha1($str);  //加密
        //$user['Token']  = $str;
        //$app_token      = json_encode($user);
        $app_token      = encrypt([
                                'app'       => 'api',
                                'user_id'   => $user_id,
                                'timestamp' => time(),
                                'ip'        => $ip,
                            ]);
        return $app_token;
    }


    public static function mkPass(string $user_password):string
    {
        $password = password_hash ($user_password,PASSWORD_DEFAULT);
        return $password;
    }


    public static function http_json($params,$url)
    {
        if (empty($url)){
            throw new \Error('URL为空');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POST,           1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($params));// 必须为字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
        $return = curl_exec($ch);
        return $return;
    }

    public static function get_order_sn($type)
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn.$type;
    }

    /**
     * 时间轴函数, Unix 时间戳
     * @param int $time 时间
     */
    public static function TranTime($time) {
        //$time = strtotime($time);
        $nowTime = time ();
        $message = '';
        //一年前
        if (idate ( 'Y', $nowTime ) != idate ( 'Y', $time )) {

            if ((date('m',$nowTime)==date('m',$time))&&(date('m',$nowTime)==date('m',$time))) {
                $message = date ( 'Y年', $time ).'的今天';
            }else{
                $message = date ( 'Y年m月d日', $time );
            }
        }
        else {
            //同一年
            $days = idate ( 'z', $nowTime ) - idate ( 'z', $time );
            switch(true){
                //一天内
                case (0 == $days):
                    $seconds = $nowTime - $time;
                    //一小时内
                    if ($seconds < 3600) {
                        //一分钟内
                        if ($seconds < 60) {
                            if (3 > $seconds) {
                                $message = '刚刚';
                                break;
                            } else {
                                $message = $seconds . '秒前';
                                break;
                            }
                        }
                        $message = intval ( $seconds / 60 ) . '分钟前';
                        break;
                    }
                    $message = idate ( 'H', $nowTime ) - idate ( 'H', $time ) . '小时前';
                    break;
                //昨天
                case (1 == $days):
                    $message = '昨天' . date ( 'H:i', $time );
                    break;
                //前天
                case (2 == $days):
                    $message = '前天 ' . date ( 'H:i', $time );
                    break;
                //7天内
                case (7 > $days):
                    $message = $days . '天前';
                    break;
                //超过7天
                default:
                    $message = date (  'n月j日 H:i', $time );
                    break;
            }
        }
        return $message;
    }


    #过滤数据库中不存在的键
   public static function createData($table,$data)
   {
       $res                   = [];
        $colums               = Schema::getColumnListing($table);
        foreach ($data as $k =>$v){
            if (in_array($k,$colums)){
                $res[$k]      = $v;
            }
        }
        return $res;
   }


    public static  function StrToBin($str){
        //1.列出每个字符
        $arr = preg_split('/(?<!^)(?!$)/u', $str);
        //2.unpack字符
        foreach($arr as &$v){
            $temp   = unpack('H*', $v);
            $v      = base_convert($temp[1], 16, 2);
            unset($temp);
        }
        return join(' ',$arr);
    }

    public static function uploadToken()
    {
        $accessKey = 'LL8hGO8LMMg_DYBKJAOMgw5YgK9LR9lMsM6VgY3W';
        $secretKey = 'sXBfhGQU11dEZHqOjpSLTLUIhkQKrtIjkUUrIDRa';
        $auth = new Auth($accessKey, $secretKey);
        $bucket = 'sub-authority';
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        return $token;
    }


// 水瓶座        1.20-2.18
// 双鱼座        2.19-3.20
// 白羊座        3.21-4.19
// 金牛座        4.20-5.20
// 双子座        5.21-6.21
// 巨蟹座        6.22-7.22
// 狮子座        7.23-8.22
// 处女座        8.23-9.22
// 天秤座        9.23-10.23
// 天蝎座        10.24-11.22
// 射手座        11.23-12.21
// 魔羯座        12.22-1.19


    public static function get_constellation($month, $day)
    {
        // 检查参数有效性
        if ($month < 1 || $month > 12 || $day < 1 || $day > 31)
        {
            return (false);
        }
        // 星座名称以及开始日期
        $signs = array(
            array( "20" => "水瓶座"),
            array( "19" => "双鱼座"),
            array( "21" => "白羊座"),
            array( "20" => "金牛座"),
            array( "21" => "双子座"),
            array( "22" => "巨蟹座"),
            array( "23" => "狮子座"),
            array( "23" => "处女座"),
            array( "23" => "天秤座"),
            array( "24" => "天蝎座"),
            array( "22" => "射手座"),
            array( "22" => "摩羯座")
        );
        list($sign_start, $sign_name) = each($signs[(int)$month-1]);
        if ($day < $sign_start) {
            list($sign_start, $sign_name) = each($signs[($month -2 < 0) ? $month = 11: $month -= 2]);
        }
        return $sign_name;
    }//函数结束




    public static function getImgUrl($hash)
    {
        if (empty($hash)){
            return 'null';
        }
//        dd($hash,strpos($hash,'http'));
        if (strpos($hash,'http')===false){
            $base = 'http://pd2ib2767.bkt.clouddn.com/';
            $path = $base.$hash;
        }else{
            $path = $hash;
        }
        return base64_encode($path);
//        return $path;
    }


    public static function getOrderType(string $order_sn)
    {
        $suffix = explode('_',$order_sn)[1];
        $type   = trim($suffix,'V');
        return $type;
    }

    public static function getTrackCode($order_sn)
    {
        $order_sn   = explode('_',$order_sn)[0];
        $str        = strtoupper(str_random(4));
        $str       .= substr($order_sn,-6);
        return $str;
    }

    public static function createCDKey($length)
    {
        $str    = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max    = strlen($strPol)-1;
        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)]; //rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }


}
